package com.ershijin.common.util;

import com.ershijin.common.entity.User;
import net.minidev.json.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;


public class UserUtils {
    public static User getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();

        JSONObject jsonUser = null;
        
        if (context.getAuthentication().getPrincipal() instanceof OAuth2AuthenticatedPrincipal) {
            jsonUser = ((OAuth2AuthenticatedPrincipal) context.getAuthentication().getPrincipal()).getAttribute("user");
        }
        if (ObjectUtils.isEmpty(jsonUser)) return null;

//        JSONObject jsonUser = (JSONObject) ((BearerTokenAuthentication) context.getAuthentication()).getTokenAttributes().get("user");
        User user = JsonUtils.toObject(jsonUser.toJSONString(), User.class);

        return  user;
    }
}
